<?php
/**
 * @description 微信获取openid
 * @Author: eecjimmy
 * @CreateTime: 2014-8-21 17:11:19
 * 使用方法:
 * 在想要调用的模块里面通过如下方法使用（建议放在Wap公共控制器里面）：
 *         if(!session('wx_openid')){
 *              // 默认使用addons_url获取得到的链接是当前模块(Wap)的，所以获取得到的插件链接是错误的，应该改为Home模块的插件控制器
 *              redirect(str_replace('Wap','Home',addons_url('Weixin://Auth/index')));
 *          }
 *          else{
 *              // do something...
 *           }
 */

namespace Addons\Weixin\Controller;

use Home\Controller\AddonsController;

define('WEIXIN_INCLUDE_PATH', ONETHINK_ADDON_PATH . 'Weixin/Include');

class AuthController extends AddonsController
{
    protected $cfg;

    public $redirect_url;

    public function _initialize()
    {
        import('Wechat', WEIXIN_INCLUDE_PATH, '.class.php');
        import('fun', WEIXIN_INCLUDE_PATH, '.php');
        $addons = _get_addons('Weixin');
        $this->cfg = json_decode($addons['config'], true);
        /** 下面这行更改为 获取 openid 成功之后返回的链接 **/
        $this->redirect_url = U('Wap/Index/test',null,true,true);
        !$this->redirect_url || $this->redirect_url = U('Home/Index/index', null, true, true);
    }

    public function index()
    {
        $url = _addons_url('Weixin://Auth/response', array('redirect_url' => $this->redirect_url), 'Home', true);
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $this->cfg['appID'] . '&redirect_uri=' . $url . '&response_type=code&scope=snsapi_base&state=#wechat_redirect';
        redirect($url);
    }

    public function response()
    {
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $this->cfg['appID'] . '&secret=' . $this->cfg['appsecret'] . '&code=' . $_GET['code'] . '&grant_type=authorization_code';
        $result = file_get_contents($url);
        $result = json_decode($result, true);
        $openid = $result['openid'];
        if ($openid) {
            session('wx_openid', $openid);
        } else {
            die('openid获取错误');
        }
        redirect($this->redirect_url);
    }

} 